// app.js
import { getLoginCode, codeToToken, checkToken, checkSession } from './service/login_api'
App({
  globalData: {
    screenWidth: 0,
    screenHeight: 0,
    statusBarHeight: 0,
    navBarHeight: 44,
    deviceRadio: 0
  },
  onLaunch: function() {
    // 获取设备信息
    const info = wx.getSystemInfoSync()
    this.globalData.screenWidth = info.screenWidth
    this.globalData.screenHeight = info.screenHeight
    this.globalData.statusBarHeight = info.statusBarHeight
    this.globalData.deviceRadio = info.screenHeight / info.screenWidth

    // 默认进行登录
    this.handleLogin()
  },
  handleLogin: async function() {
    const token = wx.getStorageSync('token')

    // 判断token是否过期
    const checkRes = token ? await checkToken() : {} 
    // 判断session是否过期
    const isSessionOut = await checkSession()

    if (!token || !isSessionOut || checkRes.errorCode) this.loginAction()
  },

  loginAction: async function() {
    // 1.获取code
    const code = await getLoginCode()
    // 2.通过code获取token
    const {token} = await codeToToken(code)
    // 3.存储token
    wx.setStorageSync('token', token)
  }

})
